﻿using System;
using System.Configuration;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;

using Sustainalytics.Portfolios.BL;
using System.Web.Http.Cors;

namespace Sustainalytics.Portfolios.Service.Controllers
{
    [EnableCors(origins: "*", headers: "*", methods: "*")]
    [RoutePrefix("api/v1/exportPortfolioSecurity")]
    public class PortfolioSecuritiesExportController : ApiController
    {
        private const string FileName = "Portfolio Securities Template.xlsx";
        private readonly IPortfolioSecuritiesImportManagement _portfolioSecuritiesImportManager;

        public PortfolioSecuritiesExportController(IPortfolioSecuritiesImportManagement portfolioSecuritiesImportManager)
        {
            _portfolioSecuritiesImportManager = portfolioSecuritiesImportManager;
        }

        [Route("")]
        public HttpResponseMessage Post()
        {
            byte[] file = _portfolioSecuritiesImportManager.GetPortfolioSecuritiesTemplate(
                FileName,
                ConfigurationManager.AppSettings["templateFolder"] + @"\Portfolio Securities Template.xlsx");
            var result = Request.CreateResponse(HttpStatusCode.OK);

            var strContent = new PushStreamContent((outStream, httpContent, contex) =>
            {
                outStream.WriteAsync(file, 0, file.Length);
                outStream.Close();
            });

            strContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
            strContent.Headers.Add("Content-Disposition", "attachement; filename=" + "PortfolioSecuritiesTemplate" + DateTime.Now.ToString("ddMMyyyy"));

            result.Content = strContent;
            return result;
        }
    }
}
